class Game {
  constructor() {
    // 蛇对象
    this.snake = new Snake()
    // 食物对象
    this.food = new Food()
    // 定时器
    this.timer = null
    // 积分
    this.score = 0
  }
  start() {
    const _this = this
    // 设置定时器让蛇不断移动
    this.timer = setInterval(() => {
      _this.snake.move()
      const dead = _this.snake.isDead()
      if (dead) {
        window.clearInterval(this.timer)
        $('.dead').show()
      }
      const eat = _this.snake.isEat(_this.food)
      if (eat) {
        // console.log('位置一致了--蛇吃到食物了');
        _this.snake.insertNewHead()
        _this.food.randomLocation()
        _this.updateScore()
      }
    }, 200)
    // 键盘控制蛇移动方向
    $(document).keydown(e => {
      const code = e.keyCode // 键码值
      switch (code) {
        case 37:
          this.snake.direction = 'left'
          break;
        case 38:
          this.snake.direction = 'up'
          break;
        case 39:
          this.snake.direction = 'right'
          break;
        case 40:
          this.snake.direction = 'down'
          break;
      }
    })
  }
  stop() {
    const _this = this
    window.clearInterval(_this.timer)
  }
  reStart() {
    window.location.reload()
  }
  // 积分
  updateScore() {
    this.score += 10
    $('#input').val('分数：' + this.score)
  }
}